<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Excel题库批量导入工具</title>
    <script src="https://unpkg.com/xlsx@0.18.5/dist/xlsx.full.min.js"></script>
    <style>
        body {
            font-family: 'Microsoft YaHei', 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
            background-color: #f5f7fa;
            margin: 0;
            padding: 20px;
        }
        .container {
            max-width: 1200px;
            margin: 0 auto;
            background: white;
            border-radius: 12px;
            box-shadow: 0 4px 20px rgba(0,0,0,0.08);
            padding: 30px;
        }
        .header {
            text-align: center;
            margin-bottom: 30px;
            color: #2c5aa0;
        }
        .upload-area {
            border: 2px dashed #2c5aa0;
            border-radius: 8px;
            padding: 40px;
            text-align: center;
            margin-bottom: 20px;
            cursor: pointer;
            transition: all 0.3s ease;
        }
        .upload-area:hover {
            background-color: #f0f4f8;
        }
        .upload-area.dragover {
            background-color: #e3f2fd;
            border-color: #1976d2;
        }
        .file-input {
            display: none;
        }
        .btn {
            background: linear-gradient(135deg, #2c5aa0 0%, #1e3a8a 100%);
            color: white;
            border: none;
            padding: 12px 24px;
            border-radius: 6px;
            cursor: pointer;
            font-size: 16px;
            margin: 10px;
        }
        .btn:hover {
            transform: translateY(-1px);
            box-shadow: 0 4px 15px rgba(0,0,0,0.2);
        }
        .format-guide {
            background: #fff3cd;
            border: 1px solid #ffeaa7;
            border-radius: 6px;
            padding: 15px;
            margin-bottom: 20px;
        }
        .preview-area {
            margin-top: 20px;
            max-height: 400px;
            overflow-y: auto;
            border: 1px solid #ddd;
            border-radius: 8px;
            padding: 15px;
            background-color: #f9f9f9;
        }
        .question-preview {
            background: white;
            border-radius: 6px;
            padding: 15px;
            margin-bottom: 10px;
            border-left: 4px solid #2c5aa0;
        }
        .output-area {
            background: #f8f9fa;
            border: 1px solid #dee2e6;
            border-radius: 6px;
            padding: 15px;
            margin-top: 20px;
            font-family: 'Courier New', monospace;
            font-size: 12px;
            max-height: 300px;
            overflow-y: auto;
        }
        .status {
            padding: 10px;
            border-radius: 6px;
            margin: 10px 0;
        }
        .status.success {
            background: #d4edda;
            border: 1px solid #c3e6cb;
            color: #155724;
        }
        .status.error {
            background: #f8d7da;
            border: 1px solid #f5c6cb;
            color: #721c24;
        }
        .status.info {
            background: #d1ecf1;
            border: 1px solid #bee5eb;
            color: #0c5460;
        }
        .sample-table {
            width: 100%;
            border-collapse: collapse;
            margin: 10px 0;
            font-size: 12px;
        }
        .sample-table th, .sample-table td {
            border: 1px solid #ddd;
            padding: 8px;
            text-align: left;
        }
        .sample-table th {
            background-color: #f2f2f2;
            font-weight: bold;
        }
    </style>
</head>
<body>
    <div class="container">
        <div class="header">
            <h1>📊 Excel题库批量导入工具</h1>
            <p>上传Excel文件，自动转换为题库格式</p>
        </div>

        <div class="format-guide">
            <h3>📋 Excel文件格式要求：</h3>
            <table class="sample-table">
                <thead>
                    <tr>
                        <th>A列</th>
                        <th>B列</th>
                        <th>C列</th>
                        <th>D列</th>
                        <th>E列</th>
                        <th>F列</th>
                        <th>G列</th>
                        <th>H列</th>
                        <th>I列</th>
                    </tr>
                </thead>
                <tbody>
                    <tr>
                        <td><strong>题型</strong></td>
                        <td><strong>学科</strong></td>
                        <td><strong>题目内容</strong></td>
                        <td><strong>选项A</strong></td>
                        <td><strong>选项B</strong></td>
                        <td><strong>选项C</strong></td>
                        <td><strong>选项D</strong></td>
                        <td><strong>正确答案</strong></td>
                        <td><strong>解析说明</strong></td>
                    </tr>
                    <tr>
                        <td>single</td>
                        <td>math</td>
                        <td>1+1等于几？</td>
                        <td>1</td>
                        <td>2</td>
                        <td>3</td>
                        <td>4</td>
                        <td>B</td>
                        <td>基础加法运算</td>
                    </tr>
                    <tr>
                        <td>multiple</td>
                        <td>chinese</td>
                        <td>下列哪些是诗人？</td>
                        <td>李白</td>
                        <td>杜甫</td>
                        <td>鲁迅</td>
                        <td>老舍</td>
                        <td>A,B</td>
                        <td>李白杜甫是唐代诗人</td>
                    </tr>
                </tbody>
            </table>
            <div style="margin-top: 15px;">
                <p><strong>📝 填写说明：</strong></p>
                <ul>
                    <li><strong>题型：</strong> single(单选) / multiple(多选) / judge(判断)</li>
                    <li><strong>学科：</strong> math(数学) / chinese(语文) / english(英语) / science(科学)</li>
                    <li><strong>正确答案：</strong> 单选填"A"，多选填"A,B"，判断题填"A"或"B"</li>
                    <li><strong>判断题：</strong> 选项A和B固定为"正确"和"错误"</li>
                </ul>
            </div>
        </div>

        <div class="upload-area" id="uploadArea">
            <p>📁 点击这里或拖拽Excel文件到此处上传</p>
            <p style="color: #666; font-size: 14px;">支持 .xlsx, .xls 格式文件</p>
            <input type="file" id="fileInput" class="file-input" accept=".xlsx,.xls" />
        </div>

        <div style="text-align: center;">
            <button class="btn" onclick="document.getElementById('fileInput').click()">📂 选择Excel文件</button>
            <button class="btn" onclick="generateDataFile()" id="generateBtn" style="display: none;">🔧 生成data.js文件</button>
            <button class="btn" onclick="copyToClipboard()" id="copyBtn" style="display: none;">📋 复制到剪贴板</button>
            <button class="btn" onclick="downloadFile()" id="downloadBtn" style="display: none;">💾 下载data.js文件</button>
        </div>

        <div id="statusArea"></div>

        <div id="previewArea" class="preview-area" style="display: none;">
            <h3>📖 题目预览（前5题）：</h3>
            <div id="questionList"></div>
        </div>

        <div id="outputArea" class="output-area" style="display: none;">
            <h3>📄 生成的代码：</h3>
            <pre id="generatedCode"></pre>
        </div>
    </div>

    <script>
        let parsedQuestions = [];
        let nextQuestionId = 16;

        // File upload handling
        const uploadArea = document.getElementById('uploadArea');
        const fileInput = document.getElementById('fileInput');

        uploadArea.addEventListener('click', () => fileInput.click());
        uploadArea.addEventListener('dragover', handleDragOver);
        uploadArea.addEventListener('drop', handleDrop);
        uploadArea.addEventListener('dragleave', () => uploadArea.classList.remove('dragover'));
        fileInput.addEventListener('change', handleFileSelect);

        function handleDragOver(e) {
            e.preventDefault();
            uploadArea.classList.add('dragover');
        }

        function handleDrop(e) {
            e.preventDefault();
            uploadArea.classList.remove('dragover');
            const files = e.dataTransfer.files;
            if (files.length > 0) {
                processFile(files[0]);
            }
        }

        function handleFileSelect(e) {
            const file = e.target.files[0];
            if (file) {
                processFile(file);
            }
        }

        function showStatus(message, type = 'info') {
            const statusArea = document.getElementById('statusArea');
            statusArea.innerHTML = `<div class="status ${type}">${message}</div>`;
        }

        function processFile(file) {
            showStatus('📤 正在读取Excel文件...', 'info');
            
            const reader = new FileReader();
            reader.onload = function(e) {
                try {
                    const data = new Uint8Array(e.target.result);
                    const workbook = XLSX.read(data, { type: 'array' });
                    const firstSheet = workbook.Sheets[workbook.SheetNames[0]];
                    const jsonData = XLSX.utils.sheet_to_json(firstSheet, { header: 1 });
                    
                    parseQuestions(jsonData);
                } catch (error) {
                    showStatus('❌ 文件读取失败：' + error.message, 'error');
                }
            };
            reader.readAsArrayBuffer(file);
        }

        function parseQuestions(data) {
            parsedQuestions = [];
            let successCount = 0;
            let errorCount = 0;
            
            showStatus('🔄 正在解析题目数据...', 'info');
            
            // Skip header row, start from row 1
            for (let i = 1; i < data.length; i++) {
                const row = data[i];
                if (!row || row.length < 8) continue;
                
                try {
                    const question = {
                        id: nextQuestionId++,
                        type: normalizeType(row[0]),
                        subject: normalizeSubject(row[1]),
                        question: row[2] || '',
                        options: [],
                        correctAnswer: null,
                        explanation: row[8] || '暂无解析'
                    };
                    
                    // Handle options based on question type
                    if (question.type === 'judge') {
                        question.options = ['正确', '错误'];
                    } else {
                        question.options = [row[3], row[4], row[5], row[6]].filter(opt => opt && opt.toString().trim());
                    }
                    
                    // Parse correct answer
                    question.correctAnswer = parseCorrectAnswer(row[7], question.type, question.options.length);
                    
                    if (question.question && question.options.length > 0) {
                        parsedQuestions.push(question);
                        successCount++;
                    } else {
                        errorCount++;
                    }
                } catch (error) {
                    errorCount++;
                    console.error(`Row ${i + 1} error:`, error);
                }
            }
            
            if (successCount > 0) {
                showStatus(`✅ 成功解析 ${successCount} 道题目${errorCount > 0 ? `，跳过 ${errorCount} 道无效题目` : ''}`, 'success');
                displayPreview();
                document.getElementById('generateBtn').style.display = 'inline-block';
            } else {
                showStatus('❌ 没有找到有效的题目数据，请检查Excel格式', 'error');
            }
        }

        function normalizeType(type) {
            if (!type) return 'single';
            const t = type.toString().toLowerCase();
            if (t.includes('multiple') || t.includes('多选')) return 'multiple';
            if (t.includes('judge') || t.includes('判断')) return 'judge';
            return 'single';
        }

        function normalizeSubject(subject) {
            if (!subject) return 'math';
            const s = subject.toString().toLowerCase();
            if (s.includes('chinese') || s.includes('语文')) return 'chinese';
            if (s.includes('english') || s.includes('英语')) return 'english';
            if (s.includes('science') || s.includes('科学')) return 'science';
            return 'math';
        }

        function parseCorrectAnswer(answer, type, optionCount) {
            if (!answer) return type === 'multiple' ? [0] : 0;
            
            const answerStr = answer.toString().toUpperCase();
            
            if (type === 'multiple') {
                const answers = [];
                if (answerStr.includes(',')) {
                    answerStr.split(',').forEach(a => {
                        const index = a.trim().charCodeAt(0) - 65;
                        if (index >= 0 && index < optionCount) answers.push(index);
                    });
                } else {
                    for (let char of answerStr) {
                        const index = char.charCodeAt(0) - 65;
                        if (index >= 0 && index < optionCount) answers.push(index);
                    }
                }
                return answers.length > 0 ? answers : [0];
            } else {
                const index = answerStr.charCodeAt(0) - 65;
                return (index >= 0 && index < optionCount) ? index : 0;
            }
        }

        function displayPreview() {
            const previewArea = document.getElementById('previewArea');
            const questionList = document.getElementById('questionList');
            
            questionList.innerHTML = '';
            
            parsedQuestions.slice(0, 5).forEach((q, index) => {
                const typeText = q.type === 'single' ? '单选题' : q.type === 'multiple' ? '多选题' : '判断题';
                const subjectText = q.subject === 'math' ? '数学' : q.subject === 'chinese' ? '语文' : q.subject === 'english' ? '英语' : '科学';
                
                const div = document.createElement('div');
                div.className = 'question-preview';
                div.innerHTML = `
                    <strong>题目 ${q.id}:</strong> ${q.question}<br>
                    <strong>类型:</strong> ${typeText} | <strong>学科:</strong> ${subjectText}<br>
                    <strong>选项:</strong> ${q.options.join(', ')}<br>
                    <strong>答案:</strong> ${Array.isArray(q.correctAnswer) ? 
                        q.correctAnswer.map(i => String.fromCharCode(65 + i)).join(',') : 
                        String.fromCharCode(65 + q.correctAnswer)}<br>
                    <strong>解析:</strong> ${q.explanation}
                `;
                questionList.appendChild(div);
            });
            
            if (parsedQuestions.length > 5) {
                const moreDiv = document.createElement('div');
                moreDiv.innerHTML = `<p><em>... 还有 ${parsedQuestions.length - 5} 道题目</em></p>`;
                questionList.appendChild(moreDiv);
            }
            
            previewArea.style.display = 'block';
        }

        function generateDataFile() {
            if (parsedQuestions.length === 0) {
                showStatus('❌ 没有题目数据可生成', 'error');
                return;
            }

            showStatus('🔧 正在生成代码...', 'info');

            let code = `// Question database\nconst questionDatabase = [\n`;
            
            // Add comment for existing questions
            code += `    // Add your existing questions here (id 1-15)\n\n`;
            
            // Add imported questions
            code += `    // Imported questions from Excel\n`;
            
            parsedQuestions.forEach((q, index) => {
                code += `    {\n`;
                code += `        id: ${q.id},\n`;
                code += `        type: '${q.type}',\n`;
                code += `        subject: '${q.subject}',\n`;
                code += `        question: '${q.question.replace(/'/g, "\\'")}',\n`;
                code += `        options: [${q.options.map(opt => `'${opt.replace(/'/g, "\\'")}'`).join(', ')}],\n`;
                code += `        correctAnswer: ${Array.isArray(q.correctAnswer) ? `[${q.correctAnswer.join(', ')}]` : q.correctAnswer},\n`;
                code += `        explanation: '${q.explanation.replace(/'/g, "\\'")}'`;
                code += `\n    }`;
                if (index < parsedQuestions.length - 1) code += ',';
                code += `\n\n`;
            });
            
            code += `];\n\n`;
            code += `// Export for use in other files\n`;
            code += `if (typeof module !== 'undefined' && module.exports) {\n`;
            code += `    module.exports = questionDatabase;\n`;
            code += `}`;
            
            document.getElementById('generatedCode').textContent = code;
            document.getElementById('outputArea').style.display = 'block';
            document.getElementById('copyBtn').style.display = 'inline-block';
            document.getElementById('downloadBtn').style.display = 'inline-block';
            
            showStatus(`✅ 成功生成包含 ${parsedQuestions.length} 道题目的代码`, 'success');
        }

        function copyToClipboard() {
            const code = document.getElementById('generatedCode').textContent;
            navigator.clipboard.writeText(code).then(() => {
                showStatus('📋 代码已复制到剪贴板！现在可以粘贴到你的data.js文件中', 'success');
            }).catch(err => {
                // Fallback for older browsers
                const textArea = document.createElement('textarea');
                textArea.value = code;
                document.body.appendChild(textArea);
                textArea.select();
                document.execCommand('copy');
                document.body.removeChild(textArea);
                showStatus('📋 代码已复制到剪贴板！', 'success');
            });
        }

        function downloadFile() {
            const code = document.getElementById('generatedCode').textContent;
            const blob = new Blob([code], { type: 'text/javascript' });
            const url = URL.createObjectURL(blob);
            const a = document.createElement('a');
            a.href = url;
            a.download = 'data.js';
            document.body.appendChild(a);
            a.click();
            document.body.removeChild(a);
            URL.revokeObjectURL(url);
            showStatus('💾 data.js文件已下载', 'success');
        }

        // Initialize
        document.addEventListener('DOMContentLoaded', function() {
            showStatus('🚀 Excel题库导入工具已就绪，请上传Excel文件', 'info');
        });
    </script>
</body>
</html>